class_name UIConsole
extends Control

@onready var text_edit: TextEdit = $TextEdit
var level: Level
@export var drop_item_id_name_dict: Dictionary[String, String] = {
	"01": "drop_compass"
}


func _ready() -> void:
	await get_tree().process_frame
	level = get_tree().current_scene as Level


func _process(delta: float) -> void:
	if Input.is_action_just_pressed("console") and not text_edit.visible:
		text_edit.visible = true
		text_edit.grab_focus()
		if level.player:
			level.player.enable_input = false
		
	if Input.is_action_just_pressed("confirm") and text_edit.visible:
		text_edit.visible = false
		text_edit.release_focus()
		var command_text = text_edit.text
		handle_command(command_text)
		text_edit.text = ""
		if level.player:
			level.player.enable_input = true
		
		
func handle_command(command_text: String):
	command_text = command_text.strip_edges()
	if command_text.begins_with("t"):
		handle_command_transfer(command_text.trim_prefix("t "))
	if command_text.begins_with("d"):
		handle_command_drop(command_text.trim_prefix("d "))
		

func handle_command_transfer(target_point_name: String):
	for point in level.all_random_points:
		if point.name.strip_edges().trim_prefix("rbp_") == target_point_name:
			level.player.global_position = point.global_position
			level.update_entity_active_process()
			break
			

func handle_command_drop(drop_item_id: String):
	if not drop_item_id_name_dict.has(drop_item_id): return
	
	var drop_item_name = drop_item_id_name_dict[drop_item_id]
	var target_drop_start_position = level.player.ray_cast_point.global_position + level.player.get_face() * Vector2.RIGHT * 32
	level.drop_item(drop_item_name, target_drop_start_position)
	
